package com.jilian.mydemo.modul.shop.ui;

import android.arch.lifecycle.Observer;
import android.arch.lifecycle.ViewModelProviders;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.jilian.mydemo.MyApplication;
import com.jilian.mydemo.R;
import com.jilian.mydemo.base.BaseActivity;
import com.jilian.mydemo.base.BaseDto;
import com.jilian.mydemo.base.BaseEventMsg;
import com.jilian.mydemo.common.dto.ProductDetailDto;
import com.jilian.mydemo.common.dto.SelectGoodDto;
import com.jilian.mydemo.common.dto.ShopDto;
import com.jilian.mydemo.common.dto.ShopListDto;
import com.jilian.mydemo.event.RxBus;
import com.jilian.mydemo.listener.CustomItemClickListener;
import com.jilian.mydemo.modul.order.viewmodel.OrderViewModel;
import com.jilian.mydemo.modul.shop.adapter.ShopCardAdapter;
import com.jilian.mydemo.utils.DisplayUtil;
import com.jilian.mydemo.utils.EmptyUtils;
import com.jilian.mydemo.utils.NumberUtils;
import com.jilian.mydemo.utils.ToastUitl;
import com.jilian.mydemo.views.RecyclerViewSpacesItemDecoration;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class ShoppingCartActivity extends BaseActivity implements CustomItemClickListener, ShopCardAdapter.CheckListener {
    private RecyclerView recyclerView;
    private ShopCardAdapter adapter;
    private LinearLayoutManager linearLayoutManager;
    private List<ProductDetailDto> datas;
    private OrderViewModel orderViewModel;
    private ImageView ivCheckAll;
    private TextView tvPrice;
    private TextView tvOk;
    private boolean isCheckAll;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        MyApplication.addActivity(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        MyApplication.removeActivity(this);
    }

    @Override
    protected void createViewModel() {
        orderViewModel = ViewModelProviders.of(this).get(OrderViewModel.class);
    }

    @Override
    public int intiLayout() {
        return R.layout.activity_shoppingcart;
    }

    @Override
    public void initView() {
        setNormalTitle("购物车", v -> finish());
        ivCheckAll = (ImageView) findViewById(R.id.iv_check_all);
        tvPrice = (TextView) findViewById(R.id.tv_price);
        tvOk = (TextView) findViewById(R.id.tv_ok);
        recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
        linearLayoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(linearLayoutManager);
        HashMap<String, Integer> map = new HashMap<>();
        map.put(RecyclerViewSpacesItemDecoration.TOP_DECORATION, DisplayUtil.dip2px(this, 10));//下间距
        recyclerView.addItemDecoration(new RecyclerViewSpacesItemDecoration(map));
        datas = new ArrayList<>();


        adapter = new ShopCardAdapter(this, datas, this, this);
        recyclerView.setAdapter(adapter);


    }

    @Override
    public void initData() {
        showLoadingDialog();
        orderViewModel.getShoppingCartProducts();
        orderViewModel.getShopListliveData().observe(this, new Observer<BaseDto<List<ProductDetailDto>>>() {
            @Override
            public void onChanged(@Nullable BaseDto<List<ProductDetailDto>> shopListDtoBaseDto) {
                hideLoadingDialog();
                if (shopListDtoBaseDto.isSuccess()) {
                    if (EmptyUtils.isNotEmpty(shopListDtoBaseDto)
                            && EmptyUtils.isNotEmpty(shopListDtoBaseDto.getData())) {
                        datas.clear();
                        datas.addAll(shopListDtoBaseDto.getData());
                        adapter.notifyDataSetChanged();
                    }
                } else {
                    ToastUitl.showImageToastTips(shopListDtoBaseDto.getMsg());
                }
            }
        });
    }

    /**
     * 购物车增加减少
     *
     * @param type
     */
    private void updateShopCart(String type, String shopCartId, int position) {
        showLoadingDialog();
        orderViewModel.updateShopCart(type, shopCartId);
        orderViewModel.getAddDelliveData().observe(this, new Observer<BaseDto>() {
            @Override
            public void onChanged(@Nullable BaseDto baseDto) {
                hideLoadingDialog();
                if (baseDto.isSuccess()) {
                    //新增
                    if ("1".equals(type)) {
                        Integer quantity = Integer.parseInt(datas.get(position).getQuantity());
                        quantity++;
                        datas.get(position).setQuantity(String.valueOf(quantity));
                        adapter.notifyDataSetChanged();
                        if (datas.get(position).isCheck()) {
                            initAllPrice();
                        }

                    }
                    //减少
                    if ("2".equals(type)) {
                        Integer quantity = Integer.parseInt(datas.get(position).getQuantity());
                        quantity--;
                        datas.get(position).setQuantity(String.valueOf(quantity));
                        adapter.notifyDataSetChanged();
                        if (datas.get(position).isCheck()) {
                            initAllPrice();
                        }

                    }
                } else {
                    ToastUitl.showImageToastTips(baseDto.getMsg());
                }

            }
        });

    }


    @Override
    public void initListener() {
        ivCheckAll.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                isCheckAll = !isCheckAll;
                if (isCheckAll) {
                    ivCheckAll.setImageResource(R.drawable.image_cart_icon_choosed);
                    for (int i = 0; i < datas.size(); i++) {
                        datas.get(i).setCheck(true);
                        adapter.notifyDataSetChanged();

                    }
                    checkCount = datas.size();
                } else {
                    ivCheckAll.setImageResource(R.drawable.image_cart_icon_unchoosed);
                    for (int i = 0; i < datas.size(); i++) {
                        datas.get(i).setCheck(false);
                        adapter.notifyDataSetChanged();
                    }
                    checkCount = 0;
                }
                initAllPrice();
            }
        });
        tvOk.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!EmptyUtils.isNotEmpty(datas) || checkCount == 0) {
                    return;
                }
                List<String> list = new ArrayList<>();

                for (int i = 0; i < datas.size(); i++) {
                    if (datas.get(i).isCheck()) {
                        //购物车ID
                        list.add(datas.get(i).getCartId());
                    }
                }
                addProductToOrder(list);
            }
        });
    }

    /**
     * 从购物车添加到订单
     *
     * @param list
     */
    private void addProductToOrder(List<String> list) {
        showLoadingDialog();
        orderViewModel.addProductToOrder(list);
        orderViewModel.getAddOrderliveData().observe(this, new Observer<BaseDto>() {
            @Override
            public void onChanged(@Nullable BaseDto baseDto) {
                hideLoadingDialog();
                if (baseDto.isSuccess()) {
                    ToastUitl.showImageToastSuccess("添加成功");

                    //选择的配件商品信息
                    SelectGoodDto selectGoodDto = new SelectGoodDto();
                    List<ProductDetailDto> detailDtoList = new ArrayList<>();
                    for (int i = 0; i < datas.size(); i++) {
                        if (datas.get(i).isCheck()) {
                            detailDtoList.add(datas.get(i));
                        }
                    }
                    selectGoodDto.setDetailDtoList(detailDtoList);
                    //通知刷新那
                    BaseEventMsg eventMsg = new BaseEventMsg();
                    eventMsg.setSelectGoodDto(selectGoodDto);
                    RxBus.getInstance().post(eventMsg);
                    MyApplication.clearSpecifyActivities(new Class[]{GoodDetailActivity.class});
                    MyApplication.clearSpecifyActivities(new Class[]{AccessoriesShopActivity.class});
                    finish();

                } else {
                    ToastUitl.showImageToastTips(baseDto.getMsg());
                }
            }
        });

    }

    @Override
    public void onItemClick(View view, int position) {

    }

    int checkCount = 0;

    @Override
    public void check(int position) {
        checkCount = 0;
        datas.get(position).setCheck(!datas.get(position).isCheck());
        adapter.notifyDataSetChanged();
        for (int i = 0; i < datas.size(

        ); i++) {
            if (datas.get(i).isCheck()) {
                checkCount++;
            }
        }
        if (checkCount == datas.size()) {
            isCheckAll = true;
            ivCheckAll.setImageResource(R.drawable.image_cart_icon_choosed);
        } else {
            isCheckAll = false;
            ivCheckAll.setImageResource(R.drawable.image_cart_icon_unchoosed);
        }
        initAllPrice();
    }


    @Override
    public void add(int position) {
        updateShopCart("1", datas.get(position).getCartId(), position);
    }

    @Override
    public void del(int position) {
        Integer quantity = Integer.parseInt(datas.get(position).getQuantity());
        if (quantity == 1) {
            return;
        }
        updateShopCart("2", datas.get(position).getCartId(), position);


    }

    /**
     * 計算總價
     */
    private void initAllPrice() {
        if (!EmptyUtils.isNotEmpty(datas)) {
            return;
        }
        double price = 0.00;
        for (int i = 0; i < datas.size(); i++) {
            if (datas.get(i).isCheck()) {
                price += (Double.parseDouble(datas.get(i).getActualPrice()) * Integer.parseInt(datas.get(i).getQuantity()));
            }
        }
        tvPrice.setText("￥" + NumberUtils.forMatNumber(price));
    }
}
